<?php

namespace app\command;

use app\model\User;
use app\model\Withdrawal;
use app\model\WithdrawalAuto;
use app\service\WxPayService;
use Exception;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use Throwable;

class UpdateWithdrawalStatusCommand extends Command
{
	protected function configure()
	{
		$this->setName('updateWithdrawalStatus')
			->setDescription('更新手动提现状态');
	}

	/**
	 * @throws Exception
	 * 执行一次性任务脚本
	 */
	protected function execute(Input $input, Output $output)
	{
		// 查询状态为4的数据
		$withdrawalList = Withdrawal::whereIn('withdrawal_status', [
			Withdrawal::WITHDRAWAL_STATUS_DOING,
			Withdrawal::WITHDRAWAL_STATUS_WAIT_AUDIT,
		])->where('status', Withdrawal::STATUS_COMPLETED)
			->select()->toArray();

		// 如果没有数据，则直接跳过
		if (empty($withdrawalList)) {
			return;
		}

		$withdrawalIds = array_column($withdrawalList, 'id');

		// 查询自动提现记录
		$withdrawalAutoList    = WithdrawalAuto::whereIn('withdrawal_id', $withdrawalIds)->select()->toArray();
		$withdrawalAutoListMap = array_column($withdrawalAutoList, null, 'withdrawal_id');

		foreach ($withdrawalList as $item) {
			$result = [];

			$withdrawalAuto = $withdrawalAutoListMap[$item['id']];

			// 查询转账订单状态
			try {
				$result = WxPayService::getInstance()->queryTransferOrder($withdrawalAuto['order_no']);
			} catch (Throwable $e) {
				// 未查到支付信息，则将状态改为 待打款 1
				if ($e->getCode() == '404') {
					$this->updateWaitPayment($item, $withdrawalAuto);
				}
			}

			if (!empty($result)) {
				switch ($result['state']) {
					case 'SUCCESS':
					case 'TRANSFERING':
						$withdrawalStatus = 2;
						$autoStatus       = 1;
						break;
					case 'CANCELLED':
					case 'CANCELING':
						$withdrawalStatus = 5;
						$autoStatus       = 3;
						break;
					default:
						$withdrawalStatus = 6;
						$autoStatus       = 2;
						break;
				}
				$updateWithdrawalAutoData = [
					'status' => $autoStatus,
				];

				$updateWithdrawalData = [
					'withdrawal_status' => $withdrawalStatus,
				];


				if (empty($withdrawalAuto['transfer_bill_no'])) {
					$updateWithdrawalAutoData['transfer_bill_no'] = $result['transfer_bill_no'];
				}

				DB::transaction(function () use ($item, $withdrawalAuto, $updateWithdrawalAutoData, $updateWithdrawalData, $withdrawalStatus) {
					// 修改自动提现表
					WithdrawalAuto::where('id', $withdrawalAuto['id'])->update($updateWithdrawalAutoData);
					// 修改提现记录表
					Withdrawal::where('id', $item['id'])->update($updateWithdrawalData);
					// 如果未提现成功，则将返还已经扣减的用户余额
					if ($withdrawalStatus != Withdrawal::WITHDRAWAL_STATUS_COMPLETED) {
						$incMoney = intval($item['withdrawal_money'] * 100);
						User::where('id', $item['user_id'])->setInc('money', $incMoney);
					}
				});
			}
			unset($withdrawalStatus);
			unset($autoStatus);
			unset($incMoney);
		}
	}

	public function updateWaitPayment($item, $withdrawalAuto)
	{
		DB::transaction(function () use ($item, $withdrawalAuto) {
			// 返还已经扣减的用户余额
			$incMoney = intval($item['withdrawal_money'] * 100);
			User::where('id', $item['user_id'])->setInc('money', $incMoney);
			// 将提现记录表中的状态 改为 取消提现
			Withdrawal::where('id', $item['id'])->update([
				'withdrawal_status' => Withdrawal::WITHDRAWAL_STATUS_CANCEL,
			]);
			// 将自动提现记录表中的状态 改为 已撤销
			WithdrawalAuto::where('id', $item['id'])->update([
				'status' => WithdrawalAuto::STATUS_CANCELED,
			]);
		});
	}
}